#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <sstream>
using namespace std;
#define HELLOWORLD 0
#define CAMERA 1
#define RECOGNIZE 0 
int main ( int argc, char **argv )
{
#if HELLOWORLD
	cvNamedWindow( "My Window", 1 );
	cout << "demo hello world" << endl;
	IplImage *img = cvCreateImage( cvSize( 640, 480 ), 8, 1 );
	CvFont font;
	double hscale = 1.0;
	double vscale = 1.0;
	int linewidth = 1;
	cvInitFont( &font, CV_FONT_HERSHEY_SIMPLEX | CV_FONT_ITALIC,
		hscale, vscale, 0, linewidth );
	cvPutText( img, "hello world!", cvPoint( 200, 400 ), &font,
        	cvScalar( 255, 255, 0 ) );
	cvShowImage( "My Window", img );
	cvWaitKey(0);
#endif
#if CAMERA
	cvNamedWindow( "My Window", 1 );
	cout << "demo camera" << endl;
	CvCapture *capture = cvCreateCameraCapture(0);
	assert(capture != 0);
	
	for(;;) {
		IplImage *img = cvQueryFrame(capture);
		if (img == 0)
			break;
		cvShowImage( "My Window", img );
		char ch = cvWaitKey(20);
		if (ch == 'q')
			break;
	}
	cvWaitKey(0);
	cvReleaseCapture(&capture);
#endif
#if RECOGNIZE 
	cout << "demo show image" << endl;
	IplImage *img = cvLoadImage("../IMGP0023.JPG", CV_LOAD_IMAGE_ANYCOLOR);
	//IplImage *img = cvLoadImage("../dice1.png", CV_LOAD_IMAGE_ANYCOLOR);
	CvSize size = cvSize(img->width, img->height);
	IplImage *img2 = cvCreateImage(size, img->depth, 1);
	assert(img2 != 0);
	cvCvtColor(img, img2, CV_BGR2GRAY);
	const int BINARY_THRESHOLD = 200;
	cvThreshold(img2, img2, BINARY_THRESHOLD, 255, CV_THRESH_BINARY);
	CvMemStorage *storage = cvCreateMemStorage(0);
	CvSeq *contour;
	cvFindContours(img2, storage, &contour, sizeof(CvContour),
		CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);
	IplImage *img3 = cvCreateImage(size, img->depth, 3);
	assert(img3 != 0);
	int i = 0;
	CvSeq *begin = contour;
	//Disproportionate size of the removed
	int maxW = 0, maxH = 0;
	int offset = 5;
	for(; contour; contour = contour->h_next) {
		CvRect rect = cvBoundingRect(contour, 1);
		if (abs(rect.width - rect.height) > offset)
			continue;
		if (rect.width > maxW)
			maxW = rect.width;
		if (rect.height > maxH)
			maxH = rect.height;	
	}
	for(contour = begin; contour; contour = contour->h_next) {
		CvRect rect = cvBoundingRect(contour, 1);
		if ((rect.width < maxW - offset) ||
			rect.width > maxW + offset)
			continue;
		if ((rect.height < maxH - offset) ||
			rect.height > maxH + offset)
			continue;
		CvPoint pt1 = cvPoint(rect.x, rect.y),
			pt2 = cvPoint(rect.x + rect.width,
				rect.y + rect.height);
		cvRectangle(img3, pt1, pt2, CV_RGB(255,0,0), 2);
		cvDrawContours(img3, contour, CV_RGB(255,0,0),
			CV_RGB(255,0,0), 0, 2, 8);
		i++;
	}
	stringstream ss;
	ss << i;
	string str = ss.str();
	cvNamedWindow( str.c_str(), 1 );
	cvShowImage( str.c_str(), img3);
	cvWaitKey(0);
#endif
	return 0;
}
